package initialize

import (
	"context"
	"fmt"
	"github.com/olivere/elastic/v7"
	"github.com/spf13/viper"
	"log"
	"os"
	"shop_srvs/goods_srv/global"
	"shop_srvs/goods_srv/model"
)

func InitEs() {
	//初始化连接
	// 这里必须将sniff设置为false，因为使用olivere/elastic连接elasticsearch时，发现连接地址命名输入的时候是地址
	// 但是连接时会自动转换成内网地址或者docker中的ip地址，导致服务连接不上
	url := fmt.Sprintf("http://%s", viper.GetString("es.address"))
	logger := log.New(os.Stdout, "mxshop", log.LstdFlags)
	var (
		err    error
		esGood model.EsGoods
		exists bool
	)
	ctx := context.Background()
	global.EsClient, err = elastic.NewClient(elastic.SetURL(url), elastic.SetSniff(false),
		elastic.SetTraceLog(logger)) //链路追踪
	if err != nil {
		panic(err)
	}

	//新建mapping和index
	exists, err = global.EsClient.IndexExists(esGood.GetIndexName()).Do(ctx)
	if err != nil {
		panic(err)
	}
	if !exists {
		// Create a new index.
		_, err = global.EsClient.CreateIndex(esGood.GetIndexName()).BodyString(esGood.GetMapping()).Do(ctx)
		if err != nil {
			panic(err)
		}
	}
}
